<?php

namespace app\api\model\dealer;

use app\common\exception\BaseException;
use app\common\model\dealer\Withdraw as WithdrawModel;
use app\api\model\user\CouponLog as CouponLogModel;

/**
 * 分销商提现明细模型
 * Class Withdraw
 * @package app\api\model\dealer
 */
class Withdraw extends WithdrawModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'update_time',
    ];

    /**
     * 获取分销商提现明细
     * @param $user_id
     * @param int $apply_status
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($user_id, $apply_status = -1)
    {
        $this->where('user_id', '=', $user_id);
        $apply_status > -1 && $this->where('apply_status', '=', $apply_status);
        return $this->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 提交申请
     * @param $user
     * @param $data
     * @return false|int
     * @throws BaseException
     */
    public function submit($user, $data)
    {
        // 数据验证
        $this->validation($data);
        //获取返现劵金额
        $coupon = CouponLogModel::getCouponLogDetail($data['coupon_id'], $user['user_id']);
        // 新增申请记录
        $this->save(array_merge($data, [
            'user_id' => $user['user_id'],
            'money' => $coupon['coupon_money'],
            'apply_status' => 10,
            'wxapp_id' => self::$wxapp_id,
        ]));
        // 更改返现劵为打款处理中
        $coupon->save(['scene' => 20, 'payment_type' => 10]);
        return true;
    }

    /**
     * 数据验证
     * @param $data
     * @throws BaseException
     */
    private function validation($data)
    {
        if (!$data['coupon_id']) {
            throw new BaseException(['msg' => '请选择返现劵']);
        }
        if ($data['pay_type'] == '20') {
            if (empty($data['alipay_name']) || empty($data['alipay_account'])) {
                throw new BaseException(['msg' => '请补全提现信息']);
            }
        } elseif ($data['pay_type'] == '30') {
            if (empty($data['bank_name']) || empty($data['bank_account']) || empty($data['bank_card'])) {
                throw new BaseException(['msg' => '请补全提现信息']);
            }
        }
    }

}